package com.webside.Advertisingstatistics.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.webside.Advertisingstatistics.config.AdvertisingStatConfig;
import com.webside.Advertisingstatistics.model.AdDailyStatEntity;
import com.webside.Advertisingstatistics.model.AdSingleStatEntity;
import com.webside.Advertisingstatistics.model.AdbrowerRecordsEntity;
import com.webside.Advertisingstatistics.model.BaDvertisementEntity;
import com.webside.Advertisingstatistics.service.AdDailyStatService;
import com.webside.Advertisingstatistics.service.AdbrowerRecordsService;
import com.webside.Advertisingstatistics.service.BaDvertisementService;
import com.webside.base.baseservice.impl.AbstractService;
import com.webside.resource.model.ResourceEntity;

/***
 * lpz 广告浏览统计
 * 
 * @author Administrator
 *
 */
@Service("AdbrowerRecordsService")
public class AdbrowerRecordsServiceImpl extends AbstractService<ResourceEntity, Long>
		implements AdbrowerRecordsService {
	@Resource(name = "mongoTemplate")
	private MongoTemplate mongoTemplate;
	@Autowired
	private AdDailyStatService adDailyStatService;
	@Autowired
	private BaDvertisementService baDvertisementService;

	// mongodb数据库名
	private DBCollection collection;

	// 设置时间格式
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
	private SimpleDateFormat dfc = new SimpleDateFormat("yyyy-MM-dd 00:00:00");

	// 通过广告资源标题精确统计当前平台今日广告总曝光量，总点击量，总独立访客总Ip等信息不写代表全部。
	@Override
	public AdbrowerRecordsEntity selectSumCollectStat(String adResourceTitle, Date Time) {
		// TODO Auto-generated method stub

		// 广告浏览统计
		collection = mongoTemplate.getCollection(AdvertisingStatConfig.collectionName);
		// 返回的数据接收统计的数据
		AdbrowerRecordsEntity adbrowerRecords = new AdbrowerRecordsEntity();
		// mongodb曝光秒数的参数
		Criteria criteria = null;
		// mongodb点击数的参数
		Criteria criteria2 = null;
		// mongodb独立访客和ip数的参数
		Criteria criteria3 = null;
		// 获取要统计的日期
		String newTodayTime = null;
		if (null != Time) {
			// 获取要统计的时间
			newTodayTime = df.format(Time);
		} else {

			Date today = new Date();
			newTodayTime = df.format(today);
		}

		Pattern pattern = Pattern.compile("^" + newTodayTime + ".*$", Pattern.CASE_INSENSITIVE);
		// 增加参数为当前日期
		criteria = Criteria.where("browerTime").regex(pattern);
		criteria2 = Criteria.where("browerTime").regex(pattern);
		criteria3 = Criteria.where("browerTime").regex(pattern);
		// 如果有名字就加入参数没有就不加
		if (null != adResourceTitle && adResourceTitle != "") {
			criteria = criteria.and("adResourceTitle").is(adResourceTitle);
			criteria2 = criteria2.and("adResourceTitle").is(adResourceTitle);
			criteria3 = criteria3.and("adResourceTitle").is(adResourceTitle);
		}
		// 统计总曝光量 b代表曝光量
		criteria = criteria.and("type").is("b");
		List<AdbrowerRecordsEntity> exposureCountList = new ArrayList<AdbrowerRecordsEntity>();
		exposureCountList = this.selectAdbrowerRecordsStat(criteria, "bao").getMappedResults();
		for (AdbrowerRecordsEntity are : exposureCountList) {
			adbrowerRecords.setExposureCount(adbrowerRecords.getExposureCount() + are.getCount());
		}
		// 统计总点击量
		criteria2 = criteria2.and("type").is("d");
		List<AdbrowerRecordsEntity> clickCountList = new ArrayList<AdbrowerRecordsEntity>();
		clickCountList = this.selectAdbrowerRecordsStat(criteria2, "dian").getMappedResults();
		for (AdbrowerRecordsEntity are : clickCountList) {
			adbrowerRecords.setClickCount(adbrowerRecords.getClickCount() + are.getCount());
		}

		// 统计总独立访客
		List<AdbrowerRecordsEntity> uVisitorsCountList = new ArrayList<AdbrowerRecordsEntity>();
		uVisitorsCountList = this.selectAdbrowerRecordsStat(criteria3, "du").getMappedResults();

		adbrowerRecords.setuVisitorsCount(uVisitorsCountList.size());

		// 统计总ip数
		List<AdbrowerRecordsEntity> ipCountList = new ArrayList<AdbrowerRecordsEntity>();
		ipCountList = this.selectAdbrowerRecordsStat(criteria3, "ip").getMappedResults();
		adbrowerRecords.setIpCount(ipCountList.size());
		return adbrowerRecords;
	}

	// 传递参数到mogodb查询广告信息
	public AggregationResults<AdbrowerRecordsEntity> selectAdbrowerRecordsStat(Criteria criteria, String mark) {
		// TODO Auto-generated method stub
		AggregationResults<AdbrowerRecordsEntity> gorupResults = null;
		Aggregation agg = null;
		if (mark.equals("bao") || mark.equals("dian")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("adpositionCode").sum("count").as("count").last("adResourceTitle")
							.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("browerTime")
							.as("browerTime"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime")
							.and("adpositionCode").previousOperation());
		} else if (mark.equals("du")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("sessionId").count().as("count").last("adResourceTitle").as("adResourceTitle")
							.last("adpositionCode").as("adpositionCode").last("browerTime").as("browerTime")
							.last("sessionId").as("sessionId"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "sessionId")
							.and("sessionId").previousOperation());
		} else if (mark.equals("ip")) {

			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("ip").count().as("count").last("adResourceTitle").as("adResourceTitle")
							.last("adpositionCode").as("adpositionCode").last("browerTime").as("browerTime")
							.last("sessionId").as("sessionId").last("ip").as("ip"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "sessionId", "ip")
							.and("ip").previousOperation());

		}
		gorupResults = mongoTemplate.aggregate(agg, AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);
		return gorupResults;

	}

	// 广告统计汇总的表格查询所有的数据
	@Override
	public List<AdDailyStatEntity> adDailyStatListAll() {
		// TODO Auto-generated method stub
		List<AdDailyStatEntity> adDailyStatList = new ArrayList<AdDailyStatEntity>();
		// 今日实时统计数据
		AdDailyStatEntity adDailyStat1 = new AdDailyStatEntity();
		// 昨日统计数据
		AdDailyStatEntity adDailyStat2 = new AdDailyStatEntity();
		// 最近90天的平均值
		AdDailyStatEntity adDailyStat3 = new AdDailyStatEntity();
		// 历史最高峰
		AdDailyStatEntity adDailyStat4 = new AdDailyStatEntity();
		// 历史累计数据
		AdDailyStatEntity adDailyStat5 = new AdDailyStatEntity();
		// 查询今日数据并加入adDailyStatList中
		// 获取今日日期
		Date todayTime = new Date();
		AdbrowerRecordsEntity are = new AdbrowerRecordsEntity();
		are = this.selectSumCollectStat("", todayTime);
		adDailyStat1.setExposureCount(are.getExposureCount());
		adDailyStat1.setPv(are.getClickCount());
		adDailyStat1.setUv(are.getuVisitorsCount());
		adDailyStat1.setIp(are.getIpCount());
		adDailyStat1.setMark(1);// 添加标示1
		// 获取昨日数据并加入
		if (null != adDailyStatService.selectYesterDayAll()) {
			adDailyStat2 = adDailyStatService.selectYesterDayAll();
		}
		adDailyStat2.setMark(2);// 添加标示2
		// 获取最近90天平均数据
		if (null != adDailyStatService.avgAdDailyStatCount()) {
			adDailyStat3 = adDailyStatService.avgAdDailyStatCount();
		}
		adDailyStat3.setMark(3);// 添加标示3
		// 获取最高峰数据
		if (null != adDailyStatService.maxAdDailyStatCount()) {
			adDailyStat4 = adDailyStatService.maxAdDailyStatCount();
		}
		adDailyStat4.setMark(4);// 添加标示4
		// 获取历史累计数据
		adDailyStat5 = adDailyStatService.sumAdDailyStatCount();
		adDailyStat5.setMark(5);// 添加标示5

		// 将获取到的5组数据存入adDailyStatList集合中
		adDailyStatList.add(adDailyStat1);
		adDailyStatList.add(adDailyStat2);
		adDailyStatList.add(adDailyStat3);
		adDailyStatList.add(adDailyStat4);
		adDailyStatList.add(adDailyStat5);
		return adDailyStatList;
	}

	// 单个广告统计数据集合
	@Override
	public List<AdSingleStatEntity> AdSingleStatList() {
		// TODO Auto-generated method stub
		// 获取单个广告统计数据集合
		List<AdSingleStatEntity> adSingleStatList = new ArrayList<AdSingleStatEntity>();
		// 获取所有广告
		List<BaDvertisementEntity> baDvertisement = new ArrayList<BaDvertisementEntity>();
		baDvertisement = baDvertisementService.selectBaDvertisementAll();
		BaDvertisementEntity baDvertisement1 = new BaDvertisementEntity();
		baDvertisement1.setId(48);
		baDvertisement1.setTitle("建筑");
		this.singleIdDada(baDvertisement1);
		// for (BaDvertisementEntity bde : baDvertisement) {
		// AdSingleStatEntity ase = new AdSingleStatEntity();
		// ase = this.singleIdDada(bde);
		// if (null != ase) {
		// adSingleStatList.add(ase);
		// }
		// }

		return adSingleStatList;
	}

	// 根据广告name在mogodb中统计出当前广告id的昨日今日平均峰值和累计的数据
	private AdSingleStatEntity singleIdDada(BaDvertisementEntity baDvertisement) {

		AdSingleStatEntity adSingleStat = new AdSingleStatEntity();
		adSingleStat.setAdId(baDvertisement.getId());// 广告id
		adSingleStat.setAdTitle(baDvertisement.getTitle());// 广告name
		/*
		 * ===================================今日数据*=============================
		 * ======
		 */
		// 获取今日日期
		Date todayTime = new Date();
		AdbrowerRecordsEntity toDayadbrowerRecords = new AdbrowerRecordsEntity();
		toDayadbrowerRecords = this.selectSumCollectStat(adSingleStat.getAdTitle(), todayTime);
		adSingleStat.setTodayExposureCount(toDayadbrowerRecords.getExposureCount());// 今日总曝光量
		adSingleStat.setTodayPv(toDayadbrowerRecords.getClickCount());// 今日总点击量
		adSingleStat.setTodayUv(toDayadbrowerRecords.getuVisitorsCount());// 今日总独立访客
		adSingleStat.setTodayIpCount(toDayadbrowerRecords.getIpCount());// 今日ip量
		/*
		 * ===================================昨日数据============================
		 */
		// 获取昨日日期
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		java.util.Date yesterdayTime = cal.getTime();
		AdbrowerRecordsEntity yesterDayadbrowerRecords = new AdbrowerRecordsEntity();
		yesterDayadbrowerRecords = this.selectSumCollectStat(adSingleStat.getAdTitle(), yesterdayTime);
		adSingleStat.setYesterdayExposureCount(yesterDayadbrowerRecords.getExposureCount());// 昨日总曝光量
		adSingleStat.setYesterdayPv(yesterDayadbrowerRecords.getClickCount());// 昨日总点击量
		adSingleStat.setYesterdayUv(yesterDayadbrowerRecords.getuVisitorsCount());// 昨日总独立访客
		adSingleStat.setYesterdayIpCount(yesterDayadbrowerRecords.getIpCount());// 昨日ip量
		/* =======================近90日平均数据****=========================== */
		// 获取昨日日期
		String newTime = dfs.format(cal.getTime());
		// 获取截止于昨日90日之前的日期
		Calendar cal2 = Calendar.getInstance();
		cal2.add(Calendar.DATE, -90);
		String oldTime = dfc.format(cal2.getTime());
		// 查询参数

		Criteria criteria = null;// 曝光量的参数

		Criteria criteria2 = null;// mongodb点击数的参数

		Criteria criteria3 = null;// mongodb独立访客和ip数的参数
		// 查询参数
		criteria = Criteria.where("browerTime").lte(newTime).gte(oldTime).and("adResourceTitle")
				.is(adSingleStat.getAdTitle());
		criteria2 = Criteria.where("browerTime").lte(newTime).gte(oldTime).and("adResourceTitle")
				.is(adSingleStat.getAdTitle());
		criteria3 = Criteria.where("browerTime").lte(newTime).gte(oldTime).and("adResourceTitle")
				.is(adSingleStat.getAdTitle());

		// 统计近90天总曝光量 b代表曝光量
		Integer bSum = 0;
		criteria = criteria.and("type").is("b");
		List<AdbrowerRecordsEntity> exposureCountListAvg = new ArrayList<AdbrowerRecordsEntity>();
		exposureCountListAvg = this.AvgAdvertisementTitle(criteria, "bao").getMappedResults();

		for (AdbrowerRecordsEntity are : exposureCountListAvg) {
			bSum += are.getCount();// 取得这90天所有的曝光数据count
		}
		adSingleStat.setAvgExposureCount(bSum / 90);// 近90日平均每日曝光
		// 统计近90天点击量d 代表点击量
		Integer dSum = 0;
		criteria2 = criteria2.and("type").is("d");
		List<AdbrowerRecordsEntity> clickCountListAvg = new ArrayList<AdbrowerRecordsEntity>();
		clickCountListAvg = this.AvgAdvertisementTitle(criteria2, "dian").getMappedResults();
		for (AdbrowerRecordsEntity are : clickCountListAvg) {
			dSum += are.getCount();// 取得这90天所有的曝光数据count
		}
		adSingleStat.setAvgPv(dSum / 90);// 近90日平均每日点击
		// 统计近90天总独立访客
		List<AdbrowerRecordsEntity> uVisitorsCountListAvg = new ArrayList<AdbrowerRecordsEntity>();
		uVisitorsCountListAvg = this.AvgAdvertisementTitle(criteria3, "du").getMappedResults();

		adSingleStat.setAvgUv(uVisitorsCountListAvg.size() / 90);// 近90日平均每日Ip

		// 统计近90天总ip数
		List<AdbrowerRecordsEntity> ipCountListAvg = new ArrayList<AdbrowerRecordsEntity>();
		ipCountListAvg = this.AvgAdvertisementTitle(criteria3, "ip").getMappedResults();
		adSingleStat.setAvgIpCount(ipCountListAvg.size() / 90);
		/*
		 * ============================历史峰值根据browerDate进行分组比较===================
		 * ==
		 */
		// 查询参数
		Criteria criteriaMax = null;// 曝光量的参数
		Criteria criteriaMax2 = null;// 点击量的参数
		Criteria criteriaMax3 = null;// 曝光量的参数
		criteriaMax = Criteria.where("adResourceTitle").is(adSingleStat.getAdTitle()).and("browerTime").lte(newTime);
		criteriaMax2 = Criteria.where("adResourceTitle").is(adSingleStat.getAdTitle()).and("browerTime").lte(newTime);
		criteriaMax3 = Criteria.where("adResourceTitle").is(adSingleStat.getAdTitle()).and("browerTime").lte(newTime);
		// 曝光量峰值
		criteriaMax = criteriaMax.and("type").is("b");
		List<AdbrowerRecordsEntity> exposureCountListMax = new ArrayList<AdbrowerRecordsEntity>();
		exposureCountListMax = this.MaxAdvertisementTitle(criteriaMax, "bao").getMappedResults();
		for (AdbrowerRecordsEntity are : exposureCountListMax) {
			adSingleStat.setMaxExposureCount(are.getCount()); // 历史曝光峰值

		}

		// 点击量峰值
		criteriaMax2 = criteriaMax2.and("type").is("d");
		List<AdbrowerRecordsEntity> clickCountListMax = new ArrayList<AdbrowerRecordsEntity>();
		clickCountListMax = this.MaxAdvertisementTitle(criteriaMax2, "dian").getMappedResults();
		for (AdbrowerRecordsEntity are : clickCountListMax) {
			adSingleStat.setMaxPv(are.getCount()); // 历史点击峰值
		}

		// 独立访客峰值
		List<AdbrowerRecordsEntity> uVisitorsCountListMax = new ArrayList<AdbrowerRecordsEntity>();
		uVisitorsCountListMax = this.MaxAdvertisementTitle(criteriaMax3, "du").getMappedResults();
		Map<String, Integer> uVMap = new HashMap<String, Integer>();
		// 去掉重复的数据
		for (AdbrowerRecordsEntity are : uVisitorsCountListMax) {
			Iterator keys = uVMap.keySet().iterator();
			int mark = 0;

			while (keys.hasNext()) {
				String key = (String) keys.next();
				if (are.getBrowerDate().toString().equals(key)) {
					mark = 1;
					break;
				}
			}
			if (mark == 0) {
				uVMap.put(are.getBrowerDate().toString(), 0);
			}
		}
		// 获取map中所有的key
		List<String> keyList = new ArrayList<String>();
		Iterator it = uVMap.entrySet().iterator();
		while (it.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
			keyList.add(entry.getKey().toString()); // 返回对应的键
		}

		// 将获取到的key与从mogodb中得到的数据进行比较和计算
		for (String key : keyList) {
			for (AdbrowerRecordsEntity are2 : uVisitorsCountListMax) {
				if (key.equals(are2.getBrowerDate().toString())) {
					uVMap.put(key, Integer.parseInt(uVMap.get(key).toString()) + 1);
				}

			}

		}

		Iterator keys = uVMap.keySet().iterator();
		while (keys.hasNext()) {
			Object key = keys.next();
			Integer value = Integer.parseInt(uVMap.get(key).toString());
			if (value > adSingleStat.getMaxUv()) {
				adSingleStat.setMaxUv(value);
			}
		}

		// 独立ip峰值
		List<AdbrowerRecordsEntity> ipCountListMax = new ArrayList<AdbrowerRecordsEntity>();
		ipCountListMax = this.MaxAdvertisementTitle(criteriaMax3, "ip").getMappedResults();
		Map<String, Integer> iPMap = new HashMap<String, Integer>();
		// 去掉重复的数据
		for (AdbrowerRecordsEntity are : ipCountListMax) {
			Iterator keysip = iPMap.keySet().iterator();
			int mark = 0;
			while (keysip.hasNext()) {
				String key = (String) keysip.next();
				if (are.getBrowerDate().toString().equals(key)) {
					mark = 1;
					break;
				}
			}
			if (mark == 0) {
				iPMap.put(are.getBrowerDate().toString(), 0);
			}
		}
		// 获取map中所有的key
		List<String> keyListIp = new ArrayList<String>();
		Iterator itIp = uVMap.entrySet().iterator();
		while (itIp.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) itIp.next();
			keyListIp.add(entry.getKey().toString()); // 返回对应的键
		}

		// 将获取到的key与从mogodb中得到的数据进行比较和计算
		for (String key : keyListIp) {
			for (AdbrowerRecordsEntity are2 : ipCountListMax) {
				if (key.equals(are2.getBrowerDate().toString())) {
					iPMap.put(key, Integer.parseInt(iPMap.get(key).toString()) + 1);
				}

			}

		}
		Iterator keysIp = iPMap.keySet().iterator();
		while (keysIp.hasNext()) {
			Object key = keysIp.next();
			Integer value = Integer.parseInt(iPMap.get(key).toString());
			if (value > adSingleStat.getMaxIpCount()) {
				adSingleStat.setMaxIpCount(value);
			}
		}
		/*
		 * ===================================历史累计数据，截止到昨天======================
		 * ======
		 */
		// 查询参数
		Criteria criteriaSum = null;// 曝光量的参数
		Criteria criteriaSum2 = null;// 点击量的参数
		Criteria criteriaSum3 = null;// 曝光量的参数
		criteriaSum = Criteria.where("adResourceTitle").is(adSingleStat.getAdTitle()).and("browerTime").lte(newTime);
		criteriaSum2 = Criteria.where("adResourceTitle").is(adSingleStat.getAdTitle()).and("browerTime").lte(newTime);
		criteriaSum3 = Criteria.where("adResourceTitle").is(adSingleStat.getAdTitle()).and("browerTime").lte(newTime);

		// 统计累计总曝光量 b代表曝光量
		Integer bCount = 0;
		criteriaSum = criteriaSum.and("type").is("b");
		List<AdbrowerRecordsEntity> exposureCountListSum = new ArrayList<AdbrowerRecordsEntity>();
		exposureCountListSum = this.SumAdvertisementTitle(criteriaSum, "bao").getMappedResults();

		for (AdbrowerRecordsEntity are : exposureCountListSum) {
			bCount += are.getCount();// 取得所有的曝光数据count
		}
		adSingleStat.setExposureCount(bCount);// 历史累计曝光
		// 统计累计总点击量d 代表点击量
		Integer dCount = 0;
		criteriaSum2 = criteriaSum2.and("type").is("d");
		List<AdbrowerRecordsEntity> clickCountListSum = new ArrayList<AdbrowerRecordsEntity>();
		clickCountListSum = this.SumAdvertisementTitle(criteriaSum2, "dian").getMappedResults();
		for (AdbrowerRecordsEntity are : clickCountListSum) {
			dCount += are.getCount();// 取得所有的曝光数据count
		}
		adSingleStat.setPv(dCount);// 近历史累计点击
		// 统计累计总独立访客
		List<AdbrowerRecordsEntity> uVisitorsCountListSum = new ArrayList<AdbrowerRecordsEntity>();
		uVisitorsCountListSum = this.SumAdvertisementTitle(criteriaSum3, "du").getMappedResults();
		adSingleStat.setUv(uVisitorsCountListSum.size());// 历史累计独立访客

		// 统计累计总ip数
		List<AdbrowerRecordsEntity> ipCountListSum = new ArrayList<AdbrowerRecordsEntity>();
		ipCountListSum = this.SumAdvertisementTitle(criteriaSum3, "ip").getMappedResults();
		adSingleStat.setIpCount(ipCountListSum.size());// 历史累计独立访客历史累计ip数

		return adSingleStat;

	}

	// 根据片名和不同的参数在mongo中查询该片的统计信息(90天的平均)
	// 传递参数到mogodb查询广告信息
	public AggregationResults<AdbrowerRecordsEntity> AvgAdvertisementTitle(Criteria criteria, String mark) {
		// TODO Auto-generated method stub
		AggregationResults<AdbrowerRecordsEntity> gorupResults = null;
		Aggregation agg = null;
		if (mark.equals("bao") || mark.equals("dian")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("adpositionCode").sum("count").as("count").last("adResourceTitle")
							.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("adpositionName")
							.as("adpositionName").last(
									"browerTime")
							.as("browerTime"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "adpositionName", "browerTime")
							.and("adpositionCode").previousOperation());
		} else if (mark.equals("du")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("sessionId").count().as("count").last("adResourceTitle").as("adResourceTitle")
							.last("adpositionCode").as("adpositionCode").last("browerTime").as("browerTime")
							.last("sessionId").as("sessionId"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "sessionId")
							.and("sessionId").previousOperation());
		} else if (mark.equals("ip")) {

			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("ip").count().as("count").last("adResourceTitle").as("adResourceTitle")
							.last("adpositionCode").as("adpositionCode").last("browerTime").as("browerTime")
							.last("sessionId").as("sessionId").last("ip").as("ip"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "sessionId", "ip")
							.and("ip").previousOperation());

		}
		gorupResults = mongoTemplate.aggregate(agg, AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);
		return gorupResults;

	}

	// 根据片名和不同的参数在mongo中查询该片的统计信息(历史峰值)
	// 传递参数到mogodb查询广告信息
	public AggregationResults<AdbrowerRecordsEntity> MaxAdvertisementTitle(Criteria criteria, String mark) {
		// TODO Auto-generated method stub
		AggregationResults<AdbrowerRecordsEntity> gorupResults = null;
		Aggregation agg = null;
		if (mark.equals("bao") || mark.equals("dian")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("browerDate").sum("count").as("count").last("adResourceTitle")
							.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("browerTime")
							.as("browerTime").last("browerDate").as("browerDate"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "browerDate")
							.and("adpositionCode").previousOperation(),
					Aggregation.sort(Sort.Direction.DESC, "count"), Aggregation.limit(1));
		} else if (mark.equals("du")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("browerDate", "sessionId").count().as("count").last("adResourceTitle")
							.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("browerTime")
							.as("browerTime").last("browerDate").as("browerDate"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "browerDate")
							.and("adpositionCode").previousOperation());
		} else if (mark.equals("ip")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("browerDate", "ip").count().as("count").last("adResourceTitle")
							.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("browerTime")
							.as("browerTime").last("browerDate").as("browerDate"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "browerDate")
							.and("adpositionCode").previousOperation());

		}
		gorupResults = mongoTemplate.aggregate(agg, AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);
		return gorupResults;

	}

	// 根据片名和不同的参数在mongo中查询该片的统计信息(历史累计)
	// 传递参数到mogodb查询广告信息
	public AggregationResults<AdbrowerRecordsEntity> SumAdvertisementTitle(Criteria criteria, String mark) {
		// TODO Auto-generated method stub
		AggregationResults<AdbrowerRecordsEntity> gorupResults = null;
		Aggregation agg = null;
		if (mark.equals("bao") || mark.equals("dian")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("adResourceTitle").sum("count").as("count").last("adResourceTitle")
							.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("browerTime")
							.as("browerTime"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime")
							.and("adpositionCode").previousOperation());
		} else if (mark.equals("du")) {
			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("sessionId").count().as("count").last("adResourceTitle").as("adResourceTitle")
							.last("adpositionCode").as("adpositionCode").last("browerTime").as("browerTime")
							.last("sessionId").as("sessionId"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "sessionId")
							.and("sessionId").previousOperation());
		} else if (mark.equals("ip")) {

			agg = Aggregation.newAggregation(Aggregation.match(criteria),
					Aggregation.group("ip").count().as("count").last("adResourceTitle").as("adResourceTitle")
							.last("adpositionCode").as("adpositionCode").last("browerTime").as("browerTime")
							.last("sessionId").as("sessionId").last("ip").as("ip"),
					Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "sessionId", "ip")
							.and("ip").previousOperation());
		}
		gorupResults = mongoTemplate.aggregate(agg, AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);
		return gorupResults;

	}

	// 广告流量趋势pv up ip (折线图)
	@Override
	public Map advertisingFlow(String adResourceTitle) {
		// TODO Auto-generated method stub
		// 存储今日和明日数据
		Map newAndOld = new HashMap();
		// 获取今日日期
		Calendar cal = Calendar.getInstance();

		// =============================查询今日的数据==============================//
		String today = df.format(cal.getTime());
		Map<String, Integer> todayData = new HashMap();
		todayData = this.flowConfig(adResourceTitle, today);
		// 今日数据存入map中
		newAndOld.put("todayData", todayData);
		// =============================查询昨日的数据==============================//
		cal.add(Calendar.DATE, -1);
		String yesterday = df.format(cal.getTime());
		Map<String, Integer> yesterdayData = new HashMap();
		yesterdayData = this.flowConfig(adResourceTitle, yesterday);
		// 昨日数据存入map中
		newAndOld.put("yesterdayData", yesterdayData);

		return newAndOld;

	}

	public Map flowConfig(String adResourceTitle, String time) {

		// TODO Auto-generated method stub
		collection = mongoTemplate.getCollection(AdvertisingStatConfig.collectionName);
		// 获取小时的格式
		// 设置时间格式
		SimpleDateFormat geshi1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat geshi2 = new SimpleDateFormat("HH");
		// 格式化参数模糊查询
		Pattern pattern;
		// =============================查询当前日期数据==============================//
		Map<String, Integer> todayData = new HashMap();
		// 初始化今日的数据集合map
		// 通过循环初始化newData
		for (int i = 0; i <= 9; i++) {
			todayData.put("pv0" + i, 0);
			todayData.put("uv0" + i, 0);
			todayData.put("ip0" + i, 0);
		}
		for (int i = 10; i <= 23; i++) {
			todayData.put("pv" + i + "", 0);
			todayData.put("uv" + i + "", 0);
			todayData.put("ip" + i + "", 0);
		}

		// 获取初始化map中所有的key
		List<String> keyList = new ArrayList<String>();
		java.util.Iterator it = todayData.entrySet().iterator();
		while (it.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
			keyList.add(entry.getKey().toString()); // 返回对应的键
		}
		// 获取今日日期
		pattern = Pattern.compile("^" + time + ".*$", Pattern.CASE_INSENSITIVE);
		Criteria criteriaToday = Criteria.where("browerTime").regex(pattern);

		//// 统计总点击量
		BasicDBObject query = new BasicDBObject();
		query.append("browerTime", pattern);
		query.append("type", "d");

		if (null != adResourceTitle && !adResourceTitle.equals("")) {
			query.append("adResourceTitle", adResourceTitle);
			criteriaToday = criteriaToday.and("adResourceTitle").is(adResourceTitle);
		}

		DBCursor cursor = collection.find(query);
		if (null != cursor) {
			int i = cursor.count();
			for (DBObject dbObj : cursor) {
				if (null != dbObj.get("browerTime") && !dbObj.get("browerTime").equals("")) {
					String hour = "";
					try {
						hour = "pv" + geshi2.format(geshi1.parse(dbObj.get("browerTime").toString()));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					// 将查询得到的小时数与map中进行对比来得到count数量
					for (String key : keyList) {
						if (key.equals(hour) || key == hour) {
							todayData.put(key, Integer.parseInt(todayData.get(key).toString())
									+ Integer.parseInt(dbObj.get("count").toString()));
							break;
						}

					}

				}
			}
		}

		/// 统计总独立访客
		List<AdbrowerRecordsEntity> uVisitorsCountList = new ArrayList<AdbrowerRecordsEntity>();
		uVisitorsCountList = this.selectAdbrowerRecordsStat(criteriaToday, "du").getMappedResults();
		for (AdbrowerRecordsEntity are : uVisitorsCountList) {
			String hour = "";
			try {
				hour = "uv" + geshi2.format(geshi1.parse(are.getBrowerTime().toString()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			for (String key : keyList) {
				if (key.equals(hour) || key == hour) {
					todayData.put(key, Integer.parseInt(todayData.get(key).toString()) + 1);
					break;
				}

			}

		}
		/// 统计总ip数
		List<AdbrowerRecordsEntity> ipCountList = new ArrayList<AdbrowerRecordsEntity>();
		ipCountList = this.selectAdbrowerRecordsStat(criteriaToday, "ip").getMappedResults();
		for (AdbrowerRecordsEntity are : ipCountList) {
			String hour = "";
			try {
				hour = "ip" + geshi2.format(geshi1.parse(are.getBrowerTime().toString()));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			for (String key : keyList) {
				if (key.equals(hour) || key == hour) {
					todayData.put(key, Integer.parseInt(todayData.get(key).toString()) + 1);
					break;
				}

			}

		}

		return todayData;
	}

	// 广告位统计 根据传来的参数查询总点击总访客总ip
	@Override
	public List<AdbrowerRecordsEntity> adpositionListAll(String period) {
		// TODO Auto-generated method stub
		// 广告浏览统计
		collection = mongoTemplate.getCollection(AdvertisingStatConfig.collectionName);
		// 广告位统计
		List<AdbrowerRecordsEntity> adpositionList = new ArrayList<AdbrowerRecordsEntity>();
		// 格式化日期
		Pattern pattern;
		// 获取今日日期
		Calendar cal = Calendar.getInstance();
		// mongodb参数
		Criteria criteria = null;
		Criteria criteria2 = null;
		switch (period) {
		// 今天
		case "j":
			String today = df.format(cal.getTime());
			pattern = Pattern.compile("^" + today + ".*$", Pattern.CASE_INSENSITIVE);
			// 查询参数
			criteria = Criteria.where("browerTime").regex(pattern);
			criteria2 = Criteria.where("browerTime").regex(pattern);
			break;
		// 昨天
		case "z":
			cal.add(Calendar.DATE, -1);
			String yesterday = df.format(cal.getTime());
			pattern = Pattern.compile("^" + yesterday + ".*$", Pattern.CASE_INSENSITIVE);
			// 查询参数
			criteria = Criteria.where("browerTime").regex(pattern);
			criteria2 = Criteria.where("browerTime").regex(pattern);
			break;
		// 最近7天
		case "yz":
			// 获取昨日日期
			cal.add(Calendar.DATE, -1);
			String newTime = dfs.format(cal.getTime());

			// 获取8日前日期
			Calendar cal2 = Calendar.getInstance();
			cal2.add(Calendar.DATE, -7);
			String oleTime = dfc.format(cal2.getTime());
			// 查询参数
			criteria = Criteria.where("browerTime").lte(newTime).gte(oleTime);
			criteria2 = Criteria.where("browerTime").lte(newTime).gte(oleTime);
			break;
		}

		// 获取总广告位name和
		Aggregation agg3 = Aggregation.newAggregation(Aggregation.match(criteria),
				Aggregation.group("adpositionCode").count().as("count").last("adResourceTitle").as("adResourceTitle")
						.last("adpositionCode").as("adpositionCode").last("adpositionName").as("adpositionName")
						.last("browerTime").as("browerTime").last("browerDate").as("browerDate"),
				Aggregation.project("count", "adResourceTitle", "adpositionCode", "adpositionName", "browerTime",
						"browerDate"));
		AggregationResults<AdbrowerRecordsEntity> gorupResults3 = mongoTemplate.aggregate(agg3,
				AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);
		adpositionList = gorupResults3.getMappedResults();

		// 获取每个广告位的点击次数
		criteria = criteria.and("type").is("d");
		List<AdbrowerRecordsEntity> clickCountList = new ArrayList<AdbrowerRecordsEntity>();
		clickCountList = this.AvgAdvertisementTitle(criteria, "dian").getMappedResults();
		for (AdbrowerRecordsEntity are : clickCountList) {
			for (AdbrowerRecordsEntity are2 : adpositionList) {
				if (are.getAdpositionCode().toString().equals(are2.getAdpositionCode().toString())) {
					are2.setClickCount(are.getCount());
				}

			}
		}

		// 获取每个广告位的独立访客总数
		Aggregation agg = Aggregation.newAggregation(Aggregation.match(criteria2),
				Aggregation.group("adpositionCode", "sessionId").count().as("count").last("adResourceTitle")
						.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("browerTime")
						.as("browerTime").last("browerDate").as("browerDate"),
				Aggregation.project("count", "adResourceTitle", "adpositionCode", "browerTime", "browerDate"));
		AggregationResults<AdbrowerRecordsEntity> gorupResults = mongoTemplate.aggregate(agg,
				AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);

		List<AdbrowerRecordsEntity> uVisitorsCountList = new ArrayList<AdbrowerRecordsEntity>();
		uVisitorsCountList = gorupResults.getMappedResults();
		Map<String, Integer> uVMap = new HashMap<String, Integer>();
		// 去掉重复的数据
		for (AdbrowerRecordsEntity are : uVisitorsCountList) {
			Iterator keys = uVMap.keySet().iterator();
			int mark = 0;
			while (keys.hasNext()) {
				String key = (String) keys.next();
				if (are.getAdpositionCode().toString().equals(key)) {
					mark = 1;
					break;
				}
			}
			if (mark == 0) {
				uVMap.put(are.getAdpositionCode().toString(), 0);
			}
		}
		// 获取map中所有的key
		List<String> keyList = new ArrayList<String>();
		Iterator it = uVMap.entrySet().iterator();
		while (it.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
			keyList.add(entry.getKey().toString()); // 返回对应的键
		}
		// 将获取到的key与从mogodb中得到的数据进行比较和计算
		for (String key : keyList) {
			for (AdbrowerRecordsEntity are2 : uVisitorsCountList) {
				if (key.equals(are2.getAdpositionCode().toString())) {
					uVMap.put(key, Integer.parseInt(uVMap.get(key).toString()) + 1);
				}

			}

		}

		// 将获取的每个广告为的独立访客量加入adpositionList中

		for (String key : keyList) {
			for (AdbrowerRecordsEntity are : adpositionList) {
				if (key.equals(are.getAdpositionCode().toString())) {
					are.setuVisitorsCount(uVMap.get(key));
				}

			}
		}

		// 获取每个广告的独立Ip总数
		Aggregation agg2 = Aggregation.newAggregation(Aggregation.match(criteria2),
				Aggregation.group("adpositionCode", "ip").count().as("count").last("adResourceTitle")
						.as("adResourceTitle").last("adpositionCode").as("adpositionCode").last("adpositionName")
						.as("adpositionName").last("browerTime").as("browerTime").last("browerDate").as("browerDate"),
				Aggregation.project("count", "adResourceTitle", "adpositionCode", "adpositionName", "browerTime",
						"browerDate"));
		AggregationResults<AdbrowerRecordsEntity> gorupResults2 = mongoTemplate.aggregate(agg2,
				AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);

		List<AdbrowerRecordsEntity> iPisitorsCountList = new ArrayList<AdbrowerRecordsEntity>();
		iPisitorsCountList = gorupResults2.getMappedResults();

		Map<String, Integer> iPMap = new HashMap<String, Integer>();
		// 去掉重复的数据
		for (AdbrowerRecordsEntity are : iPisitorsCountList) {
			Iterator keys = iPMap.keySet().iterator();
			int mark = 0;
			while (keys.hasNext()) {
				String key = (String) keys.next();
				if (are.getAdpositionCode().toString().equals(key)) {
					mark = 1;
					break;
				}
			}
			if (mark == 0) {
				iPMap.put(are.getAdpositionCode().toString(), 0);
			}
		}
		// 获取map中所有的key
		List<String> keyListIp = new ArrayList<String>();
		Iterator itIp = uVMap.entrySet().iterator();
		while (itIp.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) itIp.next();
			keyListIp.add(entry.getKey().toString()); // 返回对应的键
		}
		// 将获取到的key与从mogodb中得到的数据进行比较和计算
		for (String key : keyListIp) {
			for (AdbrowerRecordsEntity are2 : iPisitorsCountList) {
				if (key.equals(are2.getAdpositionCode().toString())) {
					iPMap.put(key, Integer.parseInt(iPMap.get(key).toString()) + 1);
				}

			}

		}
		// 将获取的每个广告为的独立访客量加入adpositionList中

		for (String key : keyListIp) {
			for (AdbrowerRecordsEntity are : adpositionList) {
				if (key.equals(are.getAdpositionCode().toString())) {
					are.setIpCount(iPMap.get(key));
				}

			}
		}
		return adpositionList;
	}

	// 根据广告名称和区域进行分组查询所有的广告 在每个区域的点击 量
	@Override
	public List<AdbrowerRecordsEntity> provinceDistributionPvList() {
		// TODO Auto-generated method stub
		// 各个地区的点击量的 统计集合
		List<AdbrowerRecordsEntity> pDPvList = new ArrayList<AdbrowerRecordsEntity>();
		// 获取昨日日期
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		String yesterday = dfs.format(cal.getTime());

		// 创建参数
		Criteria criteria = Criteria.where("browerTime").lte(yesterday).and("type").is("d");
		// 获取每个广告在各个区域的点击量
		Aggregation agg = Aggregation.newAggregation(Aggregation.match(criteria),
				Aggregation.group("adResourceId", "province").sum("count").as("count").last("adResourceId")
						.as("adResourceId").last("adResourceTitle").as("adResourceTitle").last("adpositionCode")
						.as("adpositionCode").last("browerTime").as("browerTime").last("browerDate").as("browerDate"),
				Aggregation.project("count", "adResourceId", "adResourceTitle", "adpositionCode", "browerTime",
						"browerDate"));
		AggregationResults<AdbrowerRecordsEntity> gorupResults = mongoTemplate.aggregate(agg,
				AdvertisingStatConfig.collectionName, AdbrowerRecordsEntity.class);
		pDPvList = gorupResults.getMappedResults();
		return pDPvList;
	}

}
